package com.inhim.pjhim.dowloadfile.ui;

import android.content.Intent;
import android.os.AsyncTask;
import android.support.constraint.ConstraintLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.LayoutInflater;
import android.view.View;
import android.widget.Button;
import android.widget.CheckBox;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.inhim.pjhim.R;
import com.inhim.pjhim.activity.RadioActivity;
import com.inhim.pjhim.activity.VideoActivity;
import com.inhim.pjhim.app.BaseActivity;
import com.inhim.pjhim.dowloadfile.adapter.BaseRecyclerDidViewAdapter;
import com.inhim.pjhim.dowloadfile.adapter.DownloadListDidAdapter;
import com.inhim.pjhim.dowloadfile.download.MyBusinessInfoDid;
import com.inhim.pjhim.view.CenterDialog;

import org.litepal.LitePal;

import java.util.HashMap;
import java.util.List;
import java.util.Map;

public class HaveDownloadListActivity extends BaseActivity implements BaseRecyclerDidViewAdapter.OnItemClickListener,
        DownloadListDidAdapter.NotifyDataSetChanged {
    private static final String ARG_COLUMN_COUNT = "column-count";
    // TODO: Customize parameters
    private int mColumnCount = 1;
    private DidNotDownloadFragment.OnListFragmentInteractionListener mListener;
    private static final int REQUEST_DOWNLOAD_DETAIL_PAGE = 100;

    private RecyclerView recyclerView;
    private DownloadListDidAdapter downloadListAdapter;
    private LinearLayout lin_caozuo;
    private TextView textview1, textview2;
    private boolean isCheck, isAll;
    private TextView tv_edit;
    private ImageView iv_back;
    private CenterDialog centerDialog;
    private String mType;
    private TextView tvCourse;
    @Override
    public Object offerLayout() {
        return R.layout.fragment_item_list2;
    }

    @Override
    public void onBindView() {
        iv_back=findViewById(R.id.iv_back);
        iv_back.setOnClickListener(v -> {
            setResult(ListActivity.RsultCode, new Intent());
            finish();
        });
        tv_edit = findViewById(R.id.tv_edit);
        tv_edit.setOnClickListener(v -> {
            if(lin_caozuo.getVisibility()==View.GONE){
                isCheck=true;
                downloadListAdapter.setCheck(isCheck, mDeviceHeaderMap);
                downloadListAdapter.notifyDataSetChanged();
                lin_caozuo.setVisibility(View.VISIBLE);
            }else{
                isCheck=false;
                downloadListAdapter.setCheck(isCheck, mDeviceHeaderMap);
                downloadListAdapter.notifyDataSetChanged();
                lin_caozuo.setVisibility(View.GONE);
            }
        });
        recyclerView = findViewById(R.id.rv);
        textview1 = findViewById(R.id.textview1);
        textview2 = findViewById(R.id.textview2);
        lin_caozuo = findViewById(R.id.lin_caozuo);
        textview1.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                for(int i=0;i<downloadInfoList.size();i++){
                    mDeviceHeaderMap.put(i, true);
                }
                mIsAll = true;
                downloadListAdapter.setCheck(true, mDeviceHeaderMap);
                downloadListAdapter.notifyDataSetChanged();
            }
        });
        textview2.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                setDiaglog();
            }
        });
        String title=getIntent().getStringExtra("Title");
        tvCourse=findViewById(R.id.tvCourse);
        mType=getIntent().getStringExtra("type");
        if(title!=null){
            tvCourse.setText(title);
        }
        initData();
    }

    @Override
    public void notifyChanged() {

    }

    @Override
    public void checkOnClick(boolean isCheck, int position) {
        if (!isCheck) {
            mIsAll = false;
        }
        mDeviceHeaderMap.put(position, isCheck);
    }

    @Override
    public void onBackPressed() {
        setResult(ListActivity.RsultCode, new Intent());
        finish();
        super.onBackPressed();
    }

    @Override
    public void destory() {

    }
    private boolean mIsAll;
    private MyTask mTask;
    private Map<Integer, Boolean> mDeviceHeaderMap = new HashMap<>();
    private List<MyBusinessInfoDid> downloadInfoList;
    private void setDiaglog(){
        View outerView = LayoutInflater.from( HaveDownloadListActivity.this).inflate(R.layout.dialog_deletes, null);
        Button btn_ok=outerView.findViewById(R.id.btn_ok);
        Button btn_cancel=outerView.findViewById(R.id.btn_cancel);
        btn_ok.setOnClickListener(v -> {
            centerDialog.dismiss();
            showLoading("删除中");
            if(mTask!=null){
                mTask.cancel(true);
            }
            mTask = new MyTask(mIsAll);
            mTask.execute();
        });
        btn_cancel.setOnClickListener(v -> centerDialog.dismiss());
        //防止弹出两个窗口
        if (centerDialog !=null && centerDialog.isShowing()) {
            return;
        }

        centerDialog = new CenterDialog( HaveDownloadListActivity.this, R.style.ActionSheetDialogBotoomStyle);
        //将布局设置给Dialog
        centerDialog.setContentView(outerView);
        centerDialog.show();//显示对话框
    }

    @Override
    protected void onPause() {
        super.onPause();
        //如果异步任务不为空 并且状态是 运行时  ，就把他取消这个加载任务
        if(mTask !=null && mTask.getStatus() == AsyncTask.Status.RUNNING){
            mTask.cancel(true);
        }
    }

    private class MyTask extends AsyncTask<String, Integer, String> {
        // 方法1：onPreExecute（）
        // 作用：执行 线程任务前的操作
        // 注：根据需求复写
        private boolean isBoolean;
        private String status="over";
        public MyTask(Boolean isBoolean) {
            super();
            this.isBoolean = isBoolean;
        }

        @Override
        protected void onPreExecute() {

        }
        // 方法2：doInBackground（）
        // 作用：接收输入参数、执行任务中的耗时操作、返回 线程任务执行的结果
        // 注：必须复写，从而自定义线程任务
        @Override
        protected String doInBackground(String... params) {
            // 自定义的线程任务
            // 可调用publishProgress（）显示进度, 之后将执行onProgressUpdate（）
            if (isBoolean) {
                downloadListAdapter.deleteAllFiles();
            } else {
                downloadListAdapter.deleteFiles(mDeviceHeaderMap);
            }
            getDownloadListData();
            mDeviceHeaderMap=new HashMap<>();
            if(downloadInfoList!=null){
                for(int i=0;i<downloadInfoList.size();i++){
                    mDeviceHeaderMap.put(i, false);
                }
            }
            return status;
        }

        // 方法3：onProgressUpdate（）
        // 作用：在主线程 显示线程任务执行的进度
        // 注：根据需求复写
        @Override
        protected void onProgressUpdate(Integer... progresses) {

        }
        // 方法4：onPostExecute（）
        // 作用：接收线程任务执行结果、将执行结果显示到UI组件
        // 注：必须复写，从而自定义UI操作

        @Override
        protected void onPostExecute(String result) {
            if(status.equals(result)){
                hideLoading();
                lin_caozuo.setVisibility(View.GONE);
                isCheck = false;
                if(downloadListAdapter!=null && mDeviceHeaderMap!=null){
                    downloadListAdapter.setCheck(false, mDeviceHeaderMap);
                    downloadListAdapter.notifyDataSetChanged();
                    downloadListAdapter.setDate();
                }
            }
            // UI操作
        }
        // 方法5：onCancelled()
        // 作用：将异步任务设置为：取消状态
        @Override

        protected void onCancelled() {
            hideLoading();
        }

    }

    public void initData() {
        downloadInfoList = getDownloadListData();
        mDeviceHeaderMap = new HashMap<>();
        for(int i=0;i<downloadInfoList.size();i++){
            mDeviceHeaderMap.put(i, false);
        }
        if(downloadListAdapter==null){
            downloadListAdapter = new DownloadListDidAdapter(HaveDownloadListActivity.this,mType);
            downloadListAdapter.setData(downloadInfoList);
            recyclerView.setLayoutManager(new LinearLayoutManager(HaveDownloadListActivity.this));
            recyclerView.setAdapter(downloadListAdapter);
            downloadListAdapter.setCheck(false, mDeviceHeaderMap);
            downloadListAdapter.setOnItemClickListener(this);
            downloadListAdapter.setNotifyDataSetChanged(this);
        }else{
            downloadListAdapter.setData(downloadInfoList);
            downloadListAdapter.setCheck(false, mDeviceHeaderMap);
            downloadListAdapter.notifyDataSetChanged();
        }

    }

    private List<MyBusinessInfoDid> getDownloadListData() {
        List<MyBusinessInfoDid> myBusinessInfos=LitePal.where("type = ?", mType).find(MyBusinessInfoDid.class);
        //List<MyBusinessInfoDid> myBusinessInfos = LitePal.findAll(MyBusinessInfoDid.class);
        if (myBusinessInfos.size() > 0) {
        }
        downloadInfoList=myBusinessInfos;
        return myBusinessInfos;
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if(requestCode==REQUEST_DOWNLOAD_DETAIL_PAGE){
            initData();
        }
    }


    @Override
    public void onItemClick(int position) {
        Intent intent;
        MyBusinessInfoDid data = downloadListAdapter.getData(position);
        if(data.getType().equals("2")){
            intent=new Intent(HaveDownloadListActivity.this, VideoActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        }else {
            intent=new Intent(HaveDownloadListActivity.this, RadioActivity.class);
            intent.addFlags(Intent.FLAG_ACTIVITY_REORDER_TO_FRONT);
        }
        intent.putExtra("result", data);
        startActivityForResult(intent, REQUEST_DOWNLOAD_DETAIL_PAGE);
    }
}
